﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Veteran_cms.Models;
using THS.HtmlHelpers;
namespace Veteran_cms.Controllers
{
    public class ManageCategoryController : BaseController
    {
        readonly Veterandb _ctx = new Veterandb();
        //
        // GET: /ManageAbout/
        const int PageSize = 6;
        public ActionResult Indexcategory(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var category = _ctx.categories.OrderByDescending(p => p.category_id).ToList();
            model.CategoryList = category.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.CategoryInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = category.Count() };
            return View(model);

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Paging(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var category = _ctx.categories.OrderByDescending(p => p.category_id).ToList();
            model.CategoryList = category.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.CategoryInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = category.Count() };
            return PartialView("UCCategoryList", model);
        }

        public ActionResult Details(int id)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var ctg = _ctx.categories.SingleOrDefault(c => c.category_id == id);
            if (ctg != null)
            {
                InitParentCategory(ctg.parent_id);
                return View(ctg);
            }
            ctg = new category();
            InitParentCategory(ctg.parent_id);
            return View(ctg);
            //return trang thông báo lỗi
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                // if (!IsAuthenticateAdmin())
                //   return RedirectToAction("LogOn", "AdminHome");
                var cust = _ctx.categories.SingleOrDefault(p => p.category_id == id);
                if (cust != null)
                {
                    cust.modified_date = DateTime.Now;
                    UpdateModel(cust);
                }
                _ctx.SaveChanges();
                ViewData["Msg"] = "Đã cập nhật!";
                if (cust != null)
                    InitParentCategory(cust.parent_id);
                else
                    InitParentCategory(new category());
                return View(cust);
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            // TODO: Add delete logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "AdminHome");
            var cust = _ctx.categories.SingleOrDefault(p => p.category_id == id);
            _ctx.DeleteObject(cust);
            _ctx.SaveChanges();
            return RedirectToAction("Indexcategory");
        }

        public ActionResult Create()
        {
            InitParentCategory(new category());
            return View();
        }

        //
        // POST: /FunRingManagement/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "category_id")]category cust)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            try
            {
                cust.created_date = DateTime.Now;
                cust.modified_date = DateTime.Now;
                _ctx.AddTocategories(cust);
                _ctx.SaveChanges();
                ViewData["Msg"] = "Đã tạo thành công!";
                InitParentCategory("");
                return View(cust);
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                InitParentCategory("");
                return View(cust);
            }
        }

        #region --Utitlies-
        private void InitParentCategory(object selected)
        {
            var ctg = _ctx.categories.ToList();
            ctg.Insert(0, new category());
            ViewData["categoryPanrent"] = new SelectList(ctg.AsEnumerable(), "category_id", "name", selected);
        }
        //public ActionResult DemoUpload(int id, HttpPostedFileBase uploadFile)
        //{
        //    try
        //    {
        //        // TODO: Add update logic here
        //        // if (!IsAuthenticateAdmin())
        //        //   return RedirectToAction("LogOn", "AdminHome");
        //        category cust = ctx.categories.SingleOrDefault(p => p.category_id == id);

        //        if (uploadFile != null)
        //        {
        //            // String oldImage = cust.CustomerImg;
        //            // String oldThumbImage = cust.CustomerImgThumb;
        //            //var fileName = Path.GetFileName(uploadFile.FileName);
        //            //String sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
        //            //string filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
        //            //String fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
        //            //// MakeImagesAndThumbFile(uploadFile.InputStream, filePath, fileThumbPath, 400, 300, 90, 99, 75);
        //            ////save thumbnail file
        //            //ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
        //            //ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
        //            //// uploadFile.SaveAs(fileThumbPath);
        //            //cust.CustomerImg = Utilities.PhysicalPath + sFileName;
        //            //cust.CustomerImgThumb = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
        //            //delete image
        //            //DeleteFile(Request, Utilities.VirtualPath, oldImage);
        //            //DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);
        //        }

        //        UpdateModel(cust);
        //        ctx.SaveChanges();
        //        ViewData["Msg"] = "Đã cập nhật!";
        //        return View(cust);
        //        //return RedirectToAction("IndexPartner");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}
        #endregion
    }
}
